package com.liaoyin.travel.service.task;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liaoyin.travel.dao.UsersMapper;
import com.liaoyin.travel.dao.team.TeamMapper;
import com.liaoyin.travel.dao.team.WorkerMapper;
import com.liaoyin.travel.view.moble.task.RegularWeekView;
import com.liaoyin.travel.view.moble.task.TimedTaskBackView;
import com.liaoyin.travel.view.moble.task.TimedTaskView;
import com.liaoyin.travel.base.service.BaseService;
import com.liaoyin.travel.bean.UserInfo;
import com.liaoyin.travel.business.util.TaskUtil;
import com.liaoyin.travel.dao.task.TaskMapper;
import com.liaoyin.travel.dao.task.TimingTaskParameterMapper;
import com.liaoyin.travel.entity.FileUpload;
import com.liaoyin.travel.entity.task.TaskTiming;
import com.liaoyin.travel.entity.task.TimingTaskParameter;
import com.liaoyin.travel.exception.BusinessException;
import com.liaoyin.travel.util.FileUploadUtil;
import com.liaoyin.travel.util.PartyUtil;
import com.liaoyin.travel.util.StringUtil;
import com.liaoyin.travel.view.travelMobileControlSystem.StaffInfoView;
import com.liaoyin.travel.view.travelMobileControlSystem.TaskAddView;
import com.liaoyin.travel.vo.task.SelectTimedTaskVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * 定时任务的具体参数
 *
 * @author Kuang.JiaZhuo
 * @date 2019-10-26 15:38
 */
@Service
public class TimingTaskParameterService extends BaseService<TimingTaskParameterMapper, TimingTaskParameter> {

    @Autowired
    private TaskTimingService taskTimingService;
    @Resource
    private TaskMapper taskMapper;
    @Autowired
    private TaskBusinessService taskBusinessService;
    @Resource
    UsersMapper usersMapper;
    @Resource
    TeamMapper teamMapper;
    @Resource
    WorkerMapper workerMapper;

    /**
     * @方法名：selectTimingTaskViewByWeekDay
     * @描述： 查询【星期X】需要发布的定时任务显示信息，且大于=当前时间的
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/10/27 17:26
     */
    public List<TimedTaskView> selectTimingTaskViewByWeekDay(String weekDay) {
        List<TimedTaskView> list = this.mapper.selectTimingTaskViewByWeekDay(weekDay);
        return list;
    }

    /**
     * @author 王海洋
     * @methodName: 查询当前时间需要执行的定时任务
     * @methodDesc:
     * @description:
     * @param:
     * @return
     * @create 2019-12-05 15:29
     **/
    public List<TimedTaskView> selectTimingTaskViewNow(String time){
        return this.mapper.selectTimingTaskViewNow(time);
    }

    /**
     * @author 王海洋
     * @methodName: 删除临时定时任务相关数据
     * @methodDesc:
     * @description:
     * @param:
     * @return
     * @create 2019-12-05 15:31
     **/
    public void delTempTaskParam(String id){
        this.mapper.delTaskParameter(id);
        this.mapper.delTaskReceiver(id);
        this.mapper.delTaskTiming(id);
    }

    /**
     * @方法名：selectTimedTaskBackList
     * @描述： 后台查询定时任务参数列表
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/10/28 20:30
     */
    public PageInfo<TimedTaskBackView> selectTimedTaskBackList(SelectTimedTaskVo selectTimedTaskVo) {
        UserInfo curveUserInfo = PartyUtil.getCurrentUserInfo();
        if(curveUserInfo == null) {
            throw new BusinessException("not.login");
        }
        /** 景区id */
        String scenicId = curveUserInfo.getScenicId();
        selectTimedTaskVo.setScenicId(scenicId);

        PageHelper.startPage(selectTimedTaskVo.getNum(),selectTimedTaskVo.getSize());
        List<TimedTaskBackView> list =this.mapper.selectTimedTaskBackList(selectTimedTaskVo);
        list.forEach(timedTaskBackView -> {
            List<TaskTiming> taskTimingList = this.taskTimingService.selectTaskTimingByTaskId(timedTaskBackView.getTimedTaskId(),scenicId);
            List<String> weekList = new ArrayList<>();
            for(TaskTiming taskTiming:taskTimingList){
                if(StringUtil.isNotEmpty(taskTiming.getPubWeek())){
                    String temporary  = taskTiming.getPubWeek();
                    System.err.println("temporary="+temporary);
                    weekList.add(temporary);
                }
            }
            String publisher = timedTaskBackView.getPublisher();
            String userId = timedTaskBackView.getUserId();
            //如果发布人没有查出来，则说明是主键
            if(publisher==null){
                String nickName = this.taskMapper.selectNickNameByBackUser(userId);
                timedTaskBackView.setPublisher(nickName);

            }
            //头像
            String headPicId = timedTaskBackView.getHeadPicId();
            if(headPicId==null){
                FileUpload fileUpload = FileUploadUtil.getFileUpload(userId);
                if(fileUpload!=null){
                    timedTaskBackView.setHeadPicUrl(fileUpload.getUrl());
                }
            }else{
                FileUpload fileUpload = FileUploadUtil.getFileUpload(headPicId);
                if(fileUpload!=null){
                    timedTaskBackView.setHeadPicUrl(fileUpload.getUrl());
                }
            }
            //任务接收人
            String businessId = timedTaskBackView.getBusinessId();
            Short isSpecify = timedTaskBackView.getIsSpecify();
            List<String> userIdList = this.taskBusinessService.selectUserIdByBusinessIds(isSpecify.toString(),businessId);
            String receivers = "";
            if(!userIdList.isEmpty()){
                for(String userId1:userIdList){
                    String s1 = this.taskMapper.selectNickNameByUsers(userId1);
                    if(s1!=null){
                        receivers += s1+",";
                    }
                }
                receivers = receivers.substring(0, receivers.length()-1);
            }
            if(receivers.length()>0){
                timedTaskBackView.setReceivers(receivers);
            }
            System.err.println("weekList="+weekList);
            if(weekList!=null && weekList.size()>0){
                String pubWeekStr = TaskUtil.weekSortFormat(weekList);
                timedTaskBackView.setPubWeekStr(pubWeekStr.trim());
            }
            if(taskTimingList!=null && taskTimingList.size()>0){
                timedTaskBackView.setPubTime(taskTimingList.get(0).getPubTime());
            }
//            System.err.println(timedTaskBackView);
        });
        PageInfo<TimedTaskBackView> p = new PageInfo<>(list);
        if(TaskUtil.isNotThereAnyTimedTaskBackView(selectTimedTaskVo.getNum(),p)){
            System.err.println("selectTaskListVo.getNum()="+selectTimedTaskVo.getNum());
            System.err.println("p="+p);
//			throw new BusinessException("isTheLastPage");
            return new PageInfo<>(new ArrayList<>());
        }
        return p;
    }

    /**
     * @方法名：updateTimedTaskByIdAndEnable
     * @描述： 更新定时任务启用状态
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/10/28 22:00
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateTimedTaskByIdAndEnable(String timedTaskId, String enabled) {
        TimingTaskParameter timingTaskParameter = new TimingTaskParameter();
        timingTaskParameter.setId(timedTaskId);
        timingTaskParameter.setEnabled(enabled);
        this.updateSelectiveById(timingTaskParameter);
    }

    /**
     * @方法名：selectTimedTaskById
     * @描述： 查询定时任务详情
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/10/29 9:47
     */
    public TimedTaskBackView selectTimedTaskById(String timedTaskId) {
        UserInfo curveUserInfo = PartyUtil.getCurrentUserInfo();
        if(curveUserInfo == null) {
            throw new BusinessException("not.login");
        }
        /** 景区id */
        String scenicId = curveUserInfo.getScenicId();
        TimedTaskBackView timedTaskBackView = this.mapper.selectTimedTaskById(timedTaskId);
        List<TaskTiming> taskTimingList = this.taskTimingService.selectTaskTimingByTaskId(timedTaskId,scenicId);
        List<RegularWeekView> regularWeekViewList = new ArrayList<>();
        String[] weekDays = { "星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
        for(int i=0;i<weekDays.length;i++){
            RegularWeekView regularWeekView = new RegularWeekView();
            regularWeekView.setWeekDay(weekDays[i]);
            regularWeekView.setSelectionState("0");
            for(TaskTiming taskTiming:taskTimingList){
                String pubWeek = taskTiming.getPubWeek();
                if(pubWeek.equals(weekDays[i])){
                    regularWeekView.setSelectionState("1");
                    break;
                }
            }
            regularWeekViewList.add(regularWeekView);
        }
        timedTaskBackView.setPubTime(taskTimingList.get(0).getPubTime());
        timedTaskBackView.setRegularWeekViewList(regularWeekViewList);
        return timedTaskBackView;
    }

    /**
     * @方法名：getTaskAddViewListPage
     * @描述： 获取【生成任务计划接口】的参数(带分页)
     * @作者： kjz
     * @日期： Created in 2020/4/1 17:13
     */
    public List<TaskAddView> getTaskAddViewListPage(Integer num, Integer size){
        PageHelper.startPage(num,size);
        List<TaskAddView> list = this.getTaskAddViewList();
        return list;
    }

    /**
     * @方法名：getTaskAddViewList
     * @描述： 获取【生成任务计划接口】的参数
     * @作者： kjz
     * @日期： Created in 2020/4/1 16:10
     */
    public List<TaskAddView> getTaskAddViewList() {
        List<TaskAddView> list = this.mapper.getTaskAddViewList();
        list.forEach(taskAddView -> {
            //是按？？来指定执行人员
            String assignType = taskAddView.getAssignType();
            String businessId = taskAddView.getBusinessId();
            List<String> businessIds = Arrays.asList(businessId.split(","));
            //按员工来指定
            String assignPeople = "无";
            //按部门来指定
            String department = "无";
            //按工种来指定
            String workerType = "无";
            if("指定人员".equals(assignType)){
                String parameter = this.usersMapper.selectNiceNamesByIds(businessIds);
                if(parameter!=null){
                    assignPeople = parameter;
                }
            }else if("指定部门".equals(assignType)){
                String parameter = this.teamMapper.selectTeamNamesByIds(businessIds);
                if(parameter!=null){
                    department =  parameter;
                }
            }else if("指定工种".equals(assignType)){
                String parameter = this.workerMapper.selectWorkerNameByIds(businessIds);
                if(parameter!=null){
                    workerType =  parameter;
                }
            }
            //星期
            String runWeek = getRunWeek(taskAddView.getRunWeek());

            //常规任务和临时任务的发布时间赋值
            String category = taskAddView.getCategory();
            if("常规任务".equals(category)){
                String pubTime = taskAddView.getPubTime();
                taskAddView.setRunTime(pubTime)
                        .setPubTime("无");
            }else if("临时任务".equals(category)){
                taskAddView.setRunTime("无")
                        //临时任务就不要星期了
                        .setRunWeek("无");
            }

            taskAddView.setAssignPeople(assignPeople)
                    .setDepartment(department)
                    .setWorkerType(workerType)
                    .setRunWeek(runWeek);

        });
        return list;
    }

    /**
     * @方法名：getRunWeek
     * @描述： 组装星期字符串
     * @作者： kjz
     * @日期： Created in 2020/4/1 19:10
     */
    public String getRunWeek(String runWeek) {
        String result = "";
        String weekStr = "周一,周二,周三,周四,周五,周六,周日";
        List<String> weeks = Arrays.asList(weekStr.split(","));

        if(runWeek.split(",").length==7){
            result = "周一至周日";
        }else if(runWeek.split(",").length==1){
            result = runWeek;
        }else{
            for (String week:weeks) {
                if(runWeek.indexOf(week)!=-1){
                    result += week+",";
                }
            }
            result = result.substring(0,result.length() -1);
        }
        return result;
    }
}
